/*
 * @Description: 
 * @Author: fhw
 * @Date: 2022-11-18 11:13:34
 */
import { Controller, Post, Body, HttpCode, UseFilters, Get, Query, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiBody, ApiOperation, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
import { GroupChatService } from './group-chat.service';
import { ChatUserGroupService } from 'src/chat_user_group/chat_user_group.service';
import { ChatUserService } from 'src/chat_user/chat_user.service';
import { CreateChatGroupDto, DeleteChatGroupDto, GetChatGroupPage, UpdateGroupChatDto } from './dto/group-chat.dto';
import { isEmpty, uniq } from 'ramda';
import { throwHttp } from 'src/utlis';
import { ChatUser } from 'src/chat_user/entities/chat_user.entity';
import { SysMessageService } from 'src/sys_message/sys_message.service';
import { HttpExceptionFilter } from 'src/http-exception.filter';
import { GroupChatResult } from './entities/group-chat.entity';
import { AuthGuard } from '@nestjs/passport';
@Controller('chat-group')
@ApiTags('群聊')
@ApiBearerAuth() // swagger文档设置token
export class GroupChatController {
  constructor(
    private readonly GroupChatService: GroupChatService,
    // 聊天用户
    private readonly chatUserService: ChatUserService,
    // 聊天用户群聊
    private readonly chatUserGroupService: ChatUserGroupService,
    // 系统消息
    private readonly sysMessageService: SysMessageService
  ) { }
  @Get('/chatUserGroupPage')
  @ApiResponse({
    status: 200,
    description: '用户群聊表列表',
    type: GroupChatResult,
  })
  @ApiOperation({ summary: '用户群聊表列表', operationId: 'chatUserGroupPage'  })
  @UseGuards(AuthGuard('jwt'))//jwt策略，身份鉴权
  async  getGroupChatPage(@Query() params: GetChatGroupPage) {
    return await this.GroupChatService.getGroupChatPage(params)
  }

  @HttpCode(200)
  @Post('/createGroupChat')
  @ApiQuery({
    description: '创建群聊',
    type: CreateChatGroupDto,
  })
  @ApiBody({
    description: '创建群聊',
    type: CreateChatGroupDto,
  })
  @ApiOperation({ summary: '创建群聊', operationId: 'createGroupChat'  })
  @UseFilters(new HttpExceptionFilter())
  @UseGuards(AuthGuard('jwt'))//jwt策略，身份鉴权
  async createGroupChat(@Body() params: CreateChatGroupDto,) {
    try {
      // 去重
      const userIds = uniq(params.userIds)
      const { name, manager_id } = params
      const chatUserList = await this.chatUserService.getUserFindByIds({
        ids: userIds
      })
      // 获取用户id
      const chatUserIds = chatUserList.map(item => item.id)
      // 判断用户id是否有误
      const unknownUser = userIds.filter(item => !chatUserIds.includes(item as number))
      if (!isEmpty(unknownUser)) {
        throwHttp(`${unknownUser} 用户ID不存在`)
      }
      // 创建群聊信息
      const chatUser = await this.chatUserService.getUserInfo({ id: manager_id })
      const groupChat = await this.GroupChatService.createGroupChat(params, { chatUser: chatUser } as { chatUser: ChatUser })
      // 写入用户群聊数据
      // 使用Promise.all对map返回的数据进行处理
      userIds.push(manager_id)
      const chatUserGroupParams = await Promise.all(userIds.map(async item => {
        const chatUser = await this.chatUserService.getUserInfo({ id: item })
        const params = {
          group_id: groupChat.group_id,
          userId: item,
          is_management: 0, // 管理员默认为0
          manager_id,
          chatUser
        }
        return params
      }));
      try {
        await this.chatUserGroupService.createChatUserGroup(chatUserGroupParams, { groupChat })
      } catch (error) {
        this.deleteGroupChat({ group_id: groupChat.group_id, managerId: manager_id })
        throwHttp('创建用户群聊失败')
      }
      return '创建成功'
    } catch (error) {
      throwHttp(error.message)
    }
  }
  @HttpCode(200)
  @Post('/updateGroupChat')
  @ApiQuery({
    description: '更新群聊信息',
    type: UpdateGroupChatDto,
  })
  @ApiBody({ description: '更新群聊信息', type: UpdateGroupChatDto })
  @ApiOperation({ summary: '更新群聊信息', operationId: 'updateGroupChat'  })
  @UseFilters(new HttpExceptionFilter())
  @UseGuards(AuthGuard('jwt'))//jwt策略，身份鉴权
  async updateGroupChat(@Body() body: UpdateGroupChatDto) {
    return this.GroupChatService.updateGroupChat(body)
  }

  @HttpCode(200)
  @Post('/deleteGroupChat')
  @ApiQuery({
    description: '解散群聊',
    type: DeleteChatGroupDto,
  })
  @ApiBody({ description: '解散群聊', type: DeleteChatGroupDto })
  @ApiOperation({ summary: '解散群聊', operationId: 'deleteGroupChat'  })
  @UseFilters(new HttpExceptionFilter())
  @UseGuards(AuthGuard('jwt'))//jwt策略，身份鉴权
  async deleteGroupChat(@Body() body: DeleteChatGroupDto) {
    try {
      const { group_id, managerId } = body
      const groupChat = await this.GroupChatService.getGroupChatInfo({ group_id })
      if (groupChat.managerId !== managerId) {
        throwHttp('您不是管理者，无法解散该群聊')
      }
      const { data: chatUserGroupList } = await this.chatUserGroupService.getChatUserGroupPage({ group_id })
      // 获取群主信息
      const chatUser = await this.chatUserService.getUserInfo({ id: managerId })
      // 删除用户群聊
      for (let chatUserGroup of chatUserGroupList) {
        await this.chatUserGroupService.deleteChatUserGroup({ group_id, userId: chatUserGroup.userId })
        // 消息通知，群主无需进行通知
        if (chatUserGroup.userId !== groupChat.managerId){
          const param = {
            message_title: '解散群聊',
            message_content: `群主解散${groupChat.groupChatName}群聊`,
            message_type: 2,
            created: chatUser,
            toUserId: chatUserGroup.userId,
            createdId: managerId,
            status: 0,
            message_status: 0,
            userId: chatUser.id as number
          }
         await this.sysMessageService.createSysMessage(param)
        }
      }
      // 删除群聊信息
      await this.GroupChatService.deleteGroupChat(body)
      return '成功'
    } catch (error) {
      throwHttp(error.message)
    }
  }
}
